package com.imooc.service.impl;

import com.imooc.bo.UserBo;
import com.imooc.enums.GenderEnum;
import com.imooc.mapper.UsersMapper;
import com.imooc.pojo.Users;
import com.imooc.service.UserService;
import com.imooc.utils.DateUtil;
import com.imooc.utils.MD5Utils;
import org.apache.commons.codec.digest.DigestUtils;
import org.n3r.idworker.Sid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.Random;

/**
 * <h1></h1>
 *
 * @author : dzj
 * @create: 2022-02-14 19:25
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UsersMapper usersMapper;
    @Autowired
    private Sid sid;
    public static final String USER_FACE = "https://up.enterdesk.com/2021/edpic_360_360/8f/84/19/8f8419d00e35cb803e3176259d1447fa_3.jpg";
    @Override
    public boolean queryUsernameIsExist(String username) {
    /*    try {
            Thread.sleep(new Random().nextInt(4000));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }*/
        Example example = new Example(Users.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("username",username);
        Users users = usersMapper.selectOneByExample(example);
        return users!=null;
    }
@Transactional(propagation = Propagation.REQUIRED)
    @Override
    public Users createUser(UserBo userBo) {
    Users user = new Users();
    user.setUsername(userBo.getUsername());
    user.setPassword(encryptPassword(userBo.getPassword()));
    user.setNickname(userBo.getUsername());
    user.setFace(USER_FACE);
    Date now = new Date();
    user.setCreatedTime(now);
    user.setBirthday(DateUtil.stringToDate("1900-01-01"));
    user.setSex(GenderEnum.SECRET.getType());
    user.setUpdatedTime(now);
    user.setId(sid.nextShort());
    usersMapper.insert(user);
    return user;
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
    public Users queryUser4Login(String username, String password) {
        String md5Password = encryptPassword(password);
        Example example = new Example(Users.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("username",username);
        criteria.andEqualTo("password",md5Password);
        Users users = usersMapper.selectOneByExample(example);
        return users;
    }

    private String encryptPassword(String password) {
        try {
            return MD5Utils.getMD5Str(password);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }

    }

}
